package com.will.netty.phaseITest;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @author Will
 * @description:
 *              双向通信练习  -   客户端
 * @date 2023-06-28 22:09
 * @version: 1.0
 */
@Slf4j
public class EchoClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        log.debug("client init...");
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.debug(msg.toString());
                                ByteBuf byteBuf = (ByteBuf) msg;
                                String string = byteBuf.toString(Charset.defaultCharset());
                                log.debug("客户端接收到信息：{}", string);
                            }
                        });
//                        pipeline.addLast(new StringEncoder());
                        // 需要转成 ByteBuf 传输
                        pipeline.addLast(new ChannelOutboundHandlerAdapter() {
                            @Override
                            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                ByteBuf byteBuf = ctx.alloc().buffer();
                                byteBuf.writeBytes(msg.toString().getBytes());
                                ctx.writeAndFlush(byteBuf);
                            }
                        });
                    }
                })
                .connect("127.0.0.1", 8080)
                .sync();

        Channel channel = channelFuture.channel();

        // 异步回调，异步处理关闭
        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.debug("处理客户端关闭之后的一些操作。。。");
                channel.eventLoop().shutdownGracefully();
            }
        });

        // 客户端不断向服务端发送消息
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String nextLine = scanner.nextLine();
            channel.writeAndFlush(nextLine);
            if ("q".equals(nextLine)) {
                channel.close();
                break;
            }
        }
    }
}
